package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController(value = "adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dto
     * @return
     */
    @ApiOperation("新增菜品")
    @PostMapping
    public Result save(@RequestBody DishDTO dto) {
        log.info("新增菜品:{}",dto);
        dishService.save(dto);
        //清除缓存
        Set keys = redisTemplate.keys("dish_" + dto.getCategoryId());
        redisTemplate.delete(keys);
        return Result.success();
    }

    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dto) {
        PageResult pageResult = dishService.page(dto);
        return Result.success(pageResult);
    }

    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result deleteDishByIds(@RequestParam List<Long> ids) {
        dishService.deleteDishByIds(ids);
        //清除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result getDishById(@PathVariable Long id) {
        DishVO dishVO = dishService.getDishById(id);
        return Result.success(dishVO);
    }

    @ApiOperation("修改菜品")
    @PutMapping
    public Result updateDishById(@RequestBody DishDTO dto) {
        dishService.updateDishById(dto);
        //清除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    @ApiOperation("起售和停售")
    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status, Long id) {
        DishVO dishById = dishService.getDishById(id);
        dishService.updateStatus(status,id);
        //清除缓存
        Set keys = redisTemplate.keys("dish_" + dishById.getCategoryId());
        redisTemplate.delete(keys);
        return Result.success();
    }

    @ApiOperation("根据categoryId查询数据")
    @GetMapping("/list")
    public Result getCategoryByCategoryId(Long categoryId, String name) {
        List<Dish> dish = dishService.getCategoryByCategoryIdName(categoryId,name);
        return Result.success(dish);
    }

}











